﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading.Tasks;

namespace DefeatEpidemic.Base
{
    public class ExceptionFilter : IExceptionFilter
    {

        /// <summary>
        /// 发生异常时进入
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                context.Result = new ContentResult
                {
                    Content = context.Exception.Message,//这里是把异常抛出。也可以不抛出。
                    StatusCode = StatusCodes.Status200OK,
                    ContentType = "text/html;charset=utf-8"
                };
                //Common.NLogHelper.Error("error:" + context.Exception.Message + ",stack:" + context.Exception.StackTrace);
                Common.NLogUtil.WriteDBLog(NLog.LogLevel.Error, Common.LogType.ApiRequest, "error:" + context.Exception.Message + ",stack:" + context.Exception.StackTrace, null);
            }
            context.ExceptionHandled = true;
        }

        /// <summary>
        /// 异步发生异常时进入
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            OnException(context);
            return Task.CompletedTask;
        }

    }
}
